//var scholarUrl = 'http://localhost:4004/';
//var scholarUrl = 'http://47.104.244.119:4004/';
//var scholarUrl = 'http://39.105.19.0:8000/';
var scholarUrl = 'http://43.240.136.131:8000/';

/**
 * ajax
 * 的封装
 */
var gAjax = {
    /*
	 * 资源访问地址
	 */
		//resourceUrl: "http://39.105.19.0:8000/",
	resourceUrl: "http://43.240.136.131:8000/s",
    /**
     * 后台服务地址
     */
    httpUrl: scholarUrl + 'sholar/',
    loginUrl: scholarUrl + 'sholarLogin/',

    errorCode: function (errorCode, message) {
        switch (errorCode) {
            case '10001': //登录过期
                window.location.href = "../view/search1.html?showLogin=1";
                break;
            case '10002': //登录过期
                alert("缺少请求参数！");
                break;
            case '10008': //登录过期
                alert("用户名密码错误！");
                break;
            default:
                console.log('default error');
        }
    },

    requestNoAsync: function (url, data, method) {
        return this.request(url, data, false, "POST");
    },


    /**
     * request 改为Promise
     */
    request: function (url, data, async_, method) {

        var that = this;
        var gUrl = this.httpUrl + url;

        if (!data) {
            data = {}
        }
        if (!async_) {
            async_ = true
        }
        if (!method) {
            method = "POST"
        }

        return new Promise(function (resolve, reject) {
            $.ajax({
                url: gUrl,
                data: data,
                dataType: "json",
                async: async_,
                method: method,
                headers: {
                    'content-type': 'application/x-www-form-urlencoded',
                    'Authorization': getLoginToken()
                },
                success: function (res) {
                    if (10000 == res.code) {
                        resolve(res.data);
                    }
                    else {
                        console.log("接口:" + url + " 业务错误 :" + res.data);
                        that.errorCode(res.code, res.msg);
                        //reject(res)
                    }
                },
                fail: function (err) {
                    reject(err)
                    console.log("failed")
                }
            });
        });
    },

    /**
     * 控制器 接收方式 可加 @requestbody
     */
    request2: function (url, data, async_, method) {
        var that = this;
        var gUrl = this.httpUrl + url;
        if (!data) {
            data = {}
        }
        if (!async_) {
            async_ = true
        }
        if (!method) {
            method = "POST"
        }

        return new Promise(function (resolve, reject) {
            $.ajax({
                url: gUrl,
                data: JSON.stringify(data),
                dataType: "json",
                async: async_,
                method: method,
                contentType: "application/json",
                headers: {
                    "X-Requested-With": "XMLHttpRequest",
                    'Authorization': getLoginToken()
                },
                success: function (res) {

                    if (typeof data !== 'object') {
                        data = JSON.parse(data);
                    }
                    if (10000 == res.code) {
                        resolve(res.data);
                    }
                    else {
                        console.log("接口:" + url + " 业务错误 :" + res.data);
                        that.errorCode(res.code, res.msg);
                    }
                },
                fail: function (err) {
                    reject(err)
                    console.log("failed")
                }
            });
        });
    }

};

/**
 * 获取url中的参数
 */
var getUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) {
        return decodeURI(r[2]);
    }
    return null; //返回参数值
};

/**
 * 从页面缓存中获取
 */
var getStorage = function (mKey) {
    return JSON.parse(localStorage.getItem(mKey));
};

/**
 * 向页面缓存中插入
 */
var setStorage = function (mKey, mVal) {
    localStorage.setItem(mKey, JSON.stringify(mVal));
};

/**
 * 从页面缓存中删除
 */
var removeStorage = function (mKey) {
    localStorage.removeItem(mKey);
};

/**
 * 获取当前登录用户的pid
 */
var getCurrentUserId = function () {
    return getStorage("CURRENT_USER_ID");
}

/**
 * 放置当前登录用户的pid到页面缓存
 */
var setCurrentUserId = function (userId) {
    setStorage("CURRENT_USER_ID", userId);
}

/**
 * 获取当前登录用户的信息
 */
var getCurrentUserInfo = function () {
    return getStorage("CURRENT_USER_INFO");
}

/**
 * 放置当前登录用户的信息到页面缓存
 */
var setCurrentUserInfo = function (user) {
    setStorage("CURRENT_USER_INFO", user);
}

/**
 * layui的open封装
 */
var openLayer = function (dialog, width, height, callBack) {
    var index = layer.open({
        type: 1,
        skin: 'layui-layer-rim',
        area: [width, height],
        content: $("#" + dialog),
        scrollbar: false,
        success: function (layero) {

        }
    });
    return index;
}

var openLayer2 = function (dialog, width, height, callBack) {
    var index = layer.open({
        type: 2,
        skin: 'layui-layer-rim',
        area: [width, height],
        content: dialog,
        scrollbar: false,
        success: function (layero) {
        }
    });
    return index;
}

/*gAjax.httpUrl = getStorage("MYHTTPURL");*/

/*if(!gAjax.httpUrl){
	gAjax.httpUrl = "http://th.wlmedicine.com/";
}*/


var resetLoad = function () {
    window.location.reload();
}

var getLoginToken = function () {
    return getStorage("LOGIN_USER_TOKEN");
}

var setLoginToken = function (token) {
    setStorage("LOGIN_USER_TOKEN", token);
}

var getKeyWord = function () {
    return getStorage("KEY_WORD");
}

var setKeyWord = function (token) {
    setStorage("KEY_WORD", token);
}


var nofind = function (_this) {
    _this.src = "../img/scholar/head/common-head.png";
    _this.onerror = null;
}
var nofind_ = function (_this) {
    _this.src = "../img/scholar/head/user-head.png";
    _this.onerror = null;
}

/**
 *  检查是否已经登录过期
 */
var loginCheck = function () {
    var path_ = window.location.pathname;
    if (path_.indexOf("search1.html") != -1) {
        return;
    }
    var token_ = getLoginToken();
    if (token_ == null || token_ == '' || token_ == undefined || token_ == 'undefined') {
        gAjax.errorCode("10001");
    }
    $.ajax({
        url: gAjax.httpUrl + "ajax/query",
        data: {},
        dataType: "json",
        method: "post",
        async: false,
        headers: {
            "content-type": "application/x-www-form-urlencoded",
            'Authorization': getLoginToken()
        },
        success: function (result) {
            if (result && result.code == "10000") {

            } else {
            	console.log("验证登录的code" + result.code)
            	$(".form-group").attr("style", "z-index: -1");
                $("#login-form").show();
                flag = false;
            }
        }
    });
}

var loginCheck_ = function (openLogin) {
	

	var flag=true;

    var token_ = getLoginToken();
    if (!token_) {
    	if(openLogin) {
    		$(".form-group").attr("style", "z-index: -1");
    		$("#login-form").show();
    	}
        flag = false;
    }
    $.ajax({
        url: gAjax.httpUrl + "ajax/query",
        data: {},
        dataType: "json",
        method: "post",
        async: false,
        headers: {
            "content-type": "application/x-www-form-urlencoded",
            'Authorization': getLoginToken()
        },
        success: function (result) {
            if (result && result.code == "10000") {

            } else {
            	
            	if(openLogin) {
            		$(".form-group").attr("style", "z-index: -1");
                    $("#login-form").show();
            	}
                
                flag = false;
            }
        }
    });

    return flag;
}

loginCheck();